package com.xyd.controller;

import com.xyd.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.management.relation.Role;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {


    @RequestMapping("/login")
    public ModelAndView login(User user, HttpSession session) {
        ModelAndView mv = new ModelAndView();
        session.setAttribute("user", user);
        /* mv.addObject("user", user);*/
        mv.setViewName("redirect:toList.do");
        return mv;
    }

    @RequestMapping("/toList")
    public String toList(Model model) {
        model.addAttribute("msg", "tttttttttt");
        return "list";
    }


    @RequestMapping("/testSession")
    public String testSession(HttpSession session) {
        session.setAttribute("str", "wangwu");
        return "list";
    }

    @RequestMapping("/getUsers")
    @ResponseBody
    public List<User> getUsers() {
        User user1 = new User();
        user1.setUsername("zhaoliu");
        user1.setPassword("123");

        User user2 = new User();
        user2.setUsername("zhangsan");
        user2.setPassword("222");

        User user3 = new User();
        user3.setUsername("suwukong");
        user3.setPassword("333");

        List<User> list = new ArrayList<>();
        list.add(user1);
        list.add(user2);
        list.add(user3);

        return list;
    }

    @RequestMapping("/testStr")
    @ResponseBody
    public String testStr() {
        return "testStr";
    }

    @RequestMapping("/testParam")
    public String paramTest(@RequestParam(value = "id") long id) {
        System.out.println("id====" + id);
        return null;

    }

    @RequestMapping("/showUserInfo")
    public ModelAndView showUserInfo() {
        ModelAndView mv = new ModelAndView();
        mv.setView(new MappingJackson2JsonView());
        mv.addObject(new User("张三", "abc"));
        return mv;
    }

    //重定向到方法传值
    @RequestMapping("/addUser")
    public String addUser(RedirectAttributes ra, User user) {
        ra.addFlashAttribute("user", user);
        return "redirect:/user/showUserJsonInfo.do";
    }

    @RequestMapping("/showUserJsonInfo")
    public ModelAndView showUserJsonInfo(User user) {
        ModelAndView mv = new ModelAndView();
        mv.setView(new MappingJackson2JsonView());
        mv.addObject("user", user);
        return mv;
    }


}
